/*	
Copyright (c) 2012, Jeffrey Johnston
Licensed under The MIT License (MIT)
 
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the 
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Reflection;

namespace InfiniteGeek.Util {
	[DebuggerDisplay("({ReturnType.Name}){Name} [{Value}]")]
	internal class AutoConfigProperty {
		#region Private Members

		internal readonly IEnumerable<string> prefixSearchList;
		internal readonly PropertyInfo autoprop;

		#endregion

		#region Helpers

		/// <summary>Gets the <see cref="ConfigurationSection"/> matching <paramref name="name"/>. If no matching <see cref="ConfigurationSection"/> is found, returns null.</summary>
		internal static NameValueCollection GetConfigSection(String name) {
			return ConfigurationManager.GetSection(name) as NameValueCollection;
		}

		/// <summary>Gets the specified key from the configuration provider, either fully-qualified in <c>appSettings</c> or called out in the configuration section.</summary>
		/// <param name="key">The configuration key to retrieve. Either "Fully.Qualified.Namespace.Key" or "Key".</param>
		/// <param name="defaultValue">The default value to use if the configuration value is not found.</param>
		/// <returns>The value from configuration, or <paramref name="defaultValue"/> if not found.</returns>
		/// <exception cref="ConfigurationErrorsException">Thrown when no configuration value is found, and no default value is provided.</exception>
		internal String GetString(String key, String defaultValue) {
			foreach (String keyPrefix in prefixSearchList) {
				// set configValue to the first available in search tree
				String configValue =
					// <appSettings><add key="keyPrefix.key" />
					ConfigurationManager.AppSettings.Get(String.Concat(keyPrefix, C.CLASS_SEP, key))
					??
					// <keyPrefix><add key="key" />
					(GetConfigSection(keyPrefix) == null ? null : GetConfigSection(keyPrefix).Get(key));

				if (configValue.HasValue()) {
					// config setting provided
					return configValue;
				}
			}

			// no values found in entire search list, use default
			if (defaultValue.HasValue()) {
				return defaultValue;
			}

			// no value provided and no default
			ConfigurationErrorsException ceex = new ConfigurationErrorsException(Messages.NO_VALUE_PROVIDED.FormatWith(prefixSearchList.First(), key));
			ceex.Data.Add("prefix", prefixSearchList.First()); 
			ceex.Data.Add("key", key);
			throw ceex;
		}

		#endregion

		#region Attribute Accessors

		/// <summary>Gets the <see cref="AutoConfigSectionPropertyAttribute"/> attached to this property, if present. Otherwise, null.</summary>
		internal AutoConfigSectionPropertyAttribute SectionPropertyAttribute {
			get { return autoprop.GetAttribute<AutoConfigSectionPropertyAttribute>(); }
		}

		/// <summary>Gets the <see cref="AutoConfigKeyAttribute"/> attached to this property, if present. Otherwise, null.</summary>
		internal AutoConfigKeyAttribute KeyAttribute {
			get { return autoprop.GetAttribute<AutoConfigKeyAttribute>(); }
		}

		/// <summary>Gets the <see cref="AutoConfigDefaultAttribute"/> attached to this property, if present. Otherwise, null.</summary>
		internal AutoConfigDefaultAttribute DefaultAttribute {
			get { return autoprop.GetAttribute<AutoConfigDefaultAttribute>(); }
		}

		/// <summary>Gets the <see cref="AutoConfigMultiValueAttribute"/> attached to this property, if present. Otherwise, null.</summary>
		internal AutoConfigMultiValueAttribute MultiValueAttribute {
			get { return autoprop.GetAttribute<AutoConfigMultiValueAttribute>(); }
		}

		#endregion

		#region Constructors

		/// <summary>Ensures creation of <see cref="AutoConfigProperty"/> objects with required data.</summary>
		/// <param name="prefixes">Set of string prefixes to search in configuration for the property value.</param>
		/// <param name="info">The <see cref="PropertyInfo"/> object to populate from configuration.</param>
		public AutoConfigProperty(IEnumerable<String> prefixes, PropertyInfo info) {
			prefixSearchList = prefixes;
			autoprop = info;
		}

		#endregion

		#region Properties

		/// <summary>Gets the <see cref="Type"/> of the property value.</summary>
		public Type ReturnType { get { return autoprop.PropertyType; } }

		/// <summary>Gets the name of the property from <see cref="AutoConfigSectionPropertyAttribute"/>.Name, 
		/// <see cref="AutoConfigKeyAttribute"/>.Key, or simply the <see cref="PropertyInfo"/>.Name.</summary>
		public String Name {
			get {
				if (autoprop.HasAttribute<AutoConfigSectionPropertyAttribute>()) return SectionPropertyAttribute.Name;
				if (HasKeyName) return KeyAttribute.Key;
				return autoprop.Name.Clip(C.GET_);
			}
		}

		/// <summary>Gets the value provided via <see cref="AutoConfigDefaultAttribute"/> if present. Otherwise, null.</summary>
		public String DefaultValue {
			get {
				if (DefaultAttribute == null) return null;
				if (DefaultAttribute.Value == null) return null;
				return DefaultAttribute.Value.ToString();
			}
		}

		/// <summary>Gets the value for this property from configuration. Uses <see cref="DefaultValue"/>, if applicable.</summary>
		public String Value { get { return GetString(Name, DefaultValue); } }

		/// <summary>Gets a <see cref="Action"/> that calls the set accessor for this property.</summary>
		public Action<Object> Setter {
			get { return o => autoprop.GetSetMethod(true).Invoke(null, new[] { o }); }
		}

		public override String ToString() {
			return String.Format("({0}){1} [{2}]", ReturnType.Name, Name, Value);
		}

		#endregion

		#region Attribute Detectors

		// AutoConfig Key Attribute - changes config value key from default (property name)
		/// <summary>Gets a value indicating the presence of the <see cref="AutoConfigKeyAttribute"/>
		/// meaning this property should be provided in configuration under a custom key name.</summary>
		public bool HasKeyName { get { return KeyAttribute != null; } }

		/// <summary>Gets a value indicating the presence of the <see cref="AutoConfigSectionPropertyAttribute"/>
		/// meaning this property is intended to provide direct NameValueCollection access to a ConfigSection.</summary>
		/// <exception cref="ConfigurationErrorsException">Thrown when <see cref="AutoConfigSectionPropertyAttribute"/> is present but <see cref="ReturnType"/> is not <see cref="NameValueCollection"/>.</exception>
		public bool IsConfigSection {
			get {
				if (SectionPropertyAttribute == null) {
					return false;
				}

				// covers CustomConfigSection:ConfigurationSection
				Boolean actualSection = typeof(ConfigurationSection).IsAssignableFrom(ReturnType);

				// covers simple NameValueCollection sections
				Boolean nameValueSection = ReturnType == typeof(NameValueCollection);

				if (actualSection || nameValueSection) {
					return true;
				}

				// attribute present but property not correct type
				throw new ConfigurationErrorsException(Messages.SECTION_NOT_COLLECTION.FormatWith(Name));
			}
		}

		/// <summary>Gets a value indicating the presence of the <see cref="AutoConfigMultiValueAttribute"/>
		/// meaning this property is intended to parse a delimited list of values.</summary>
		public bool IsMultiValue { get { return MultiValueAttribute != null; } }

		/// <summary>Gets a value indicating the presence of the <see cref="AutoConfigDefaultAttribute"/>
		/// meaning this property will have a value if none is provided in configuration.</summary>
		public bool HasDefaultValue {
			get {
				// explode on wrong default attributes
				if (autoprop.HasAttribute<DefaultSettingValueAttribute>()) {
					throw new ConfigurationErrorsException(Messages.WRONG_DEFAULT_ATTRIBUTE.FormatWith(Name));
				}

				// AutoConfigDefaultAttribute inherits DefaultValueAttribute so only checking DefaultValueAttribute is false positive
				if (autoprop.HasAttribute<DefaultValueAttribute>() && DefaultValue == null) {
					throw new ConfigurationErrorsException(Messages.WRONG_DEFAULT_ATTRIBUTE.FormatWith(Name));
				}

				return DefaultAttribute != null;
			}
		}

		#endregion

		#region Value Setters

		/// <summary>Passes the configuration section to the property's set accessor.</summary>
		/// <exception cref="ConfigurationErrorsException">Thrown when <see cref="ConfigurationSection"/> is not found.</exception>
		internal void ReturnConfigSection() {
			if (typeof(ConfigurationSection).IsAssignableFrom(ReturnType)) {
				ConfigurationSection section = ConfigurationManager.GetSection(Name) as ConfigurationSection;
				if (section != null) {
					Setter(section);
					return;
				}
			}

			NameValueCollection nvcSection =
				GetConfigSection(Name)
				??
				prefixSearchList
					.Select(prefix => String.Concat(prefix, C.CLASS_SEP, Name))
					.Select(GetConfigSection)
					.FirstOrDefault(s => s != null);

			if (nvcSection == null) {
				// section not provided in config
				throw new ConfigurationErrorsException(Messages.SECTION_NOT_SECTION.FormatWith(Name));
			}

			Setter(nvcSection);
		}

		/// <summary>Parses the delimited list to the correct return type and passes to the property's set accessor.</summary>
		internal void ReturnMultiValue() {
			// split multi-value to string array, works fine with 1 item
			String[] values = Value.Split(MultiValueAttribute.Delimiter).TrimAll().ToArray();

			var resultType = new {
				IsList = ReturnType.IsGenericType && (ReturnType.GetGenericTypeDefinition() == typeof(IList<>) || ReturnType.GetGenericTypeDefinition() == typeof(List<>)),
				IsEnumerable = ReturnType.IsGenericType && ReturnType.GetGenericTypeDefinition().GetInterface("IEnumerable") == typeof(IEnumerable),
				IsArray = ReturnType.IsArray && ReturnType.HasElementType
			};

			Type elementType = null;

			if (resultType.IsList || resultType.IsEnumerable) {
				elementType = ReturnType.GetGenericArguments().First();
			} else if (resultType.IsArray) {
				elementType = ReturnType.GetElementType();
			} 

			if (elementType == null) {
				throw new ConfigurationErrorsException(Messages.MULTIVALUE_NOT_ARRAY.FormatWith(Name));
			}

			// create new array of proper destination type
			Array arr = Array.CreateInstance(elementType, values.Length);

			// convert each string item, copy to new array
			values.Select(v => Convert.ChangeType(v, elementType)).ToArray().CopyTo(arr, 0);

			// if destination is array, we're already done
			if (resultType.IsArray) {
				Setter(arr);
				return;
			}

			// construct proper result collection type
			Type genericType = typeof(List<>).MakeGenericType(new[] { elementType });
			Setter(Activator.CreateInstance(genericType, arr));

			// wanted to get to basic IEnumerable so that it could construct many things, but no good
			// MethodInfo enumerableizer = typeof(Enumerable).GetMethod("AsEnumerable");
			// object enumerable = enumerableizer.Invoke(null, new[] { Activator.CreateInstance(genericType, arr) });
			//    = "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true."
		}

		/// <summary>Determines intended use of property and causes appropriate value to be passed to set accessor.</summary>
		public void SetPropertyValue() {
			if (IsConfigSection) {
				ReturnConfigSection();
				return;
			}
			
			if (IsMultiValue) {
				ReturnMultiValue();
				return;
			}

			// strings are simple
			if (ReturnType == typeof(String)) {
				Setter(Value);
				return;
			}

			// attempt simple cast to destination type, should work for all value types
			try {
				Setter(Convert.ChangeType(Value, ReturnType));
				return;
			} catch (OverflowException) {
				throw;
			} catch (Exception) // InvalidCastException, FormatException
			{
				Setter(null);
			}

			// special enum parsing
			if (ReturnType.IsEnum) {
				ReturnEnum();
				return;
			}

			// if the value is another type, get Parse(String) method for its type and invoke
			try {
				// parse value to correct type (remains boxed)
				Setter(StringParser(Value));
			} catch (TargetInvocationException tix) {
				throw new ConfigurationErrorsException(Messages.UNPARSEABLE_VALUE.FormatWith(Name, Value, ReturnType.ToString()), tix.InnerException);
			}
		}

		/// <summary>Gets the Parse(String) method for the property's return type.</summary>
		internal Func<String, Object> StringParser {
			get {
				MethodInfo miParse = ReturnType.GetMethod(C.PARSE, new[] { typeof(String) });

				if (miParse == null) {
					// no Parse() for the property's type, we can't parse
					throw new ConfigurationErrorsException(Messages.UNPARSEABLE_TYPE.FormatWith(Name, ReturnType.ToString()));
				}

				return o => miParse.Invoke(null, new Object[] { o });
			}
		}

		/// <summary>Gets the current value of the property.</summary>
		internal object CurrentValue { get { return autoprop.GetValue(autoprop, null); } }

		/// <summary>Converts the configuration value to the specified enum type and sends to Set method.</summary>
		internal void ReturnEnum() {
			try {
				// removes "EnumType." from "EnumType.EnumValue"
				Int32 iValue = (Int32)Enum.Parse(ReturnType, Value.Clip(ReturnType.Name + C.CLASS_SEP), true);
				Setter(iValue);
			} catch (Exception ex) {
				throw new ConfigurationErrorsException(Messages.UNPARSEABLE_VALUE.FormatWith(Name, Value, ReturnType.ToString()), ex);
			}
		}

		#endregion
	}
}